﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaskelot.SP.Model.Client;
using Kaskelot.SP.Model.Client.Forms;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;
using Kaskelot.SP.Core;

namespace Kaskelot.SP.Services.Client.Mapping
{
	public static class ClientMaterielExtensions
	{
		public static ClientMateriel ToClientContract(this Materiel entity)
		{
			ClientMateriel b = new ClientMateriel();

			CopyFromEntity(entity, b, false);

			return b;
		}

		public static ClientMateriel ToMinimalClientContract(this Materiel entity)
		{
			ClientMateriel b = new ClientMateriel();

			CopyFromEntity(entity, b, true);

			return b;
		}

		public static Materiel ToContract(this ClientMateriel b)
		{
			Materiel entity = new Materiel();

			CopyToEntity(b, entity);

			return entity;
		}

		public static Materiel UpdateContract(this Materiel l, MaterielForm form)
		{
			if (l.Id == Guid.Empty)
				l.Id = Guid.NewGuid();

			l.ByggnadId = new Guid(form.ByggnadId);
			l.Antal = form.Antal;

			if (String.IsNullOrEmpty(form.FritextBeskrivning))
			{
				l.MaterielTypId = new Guid(form.MaterielTypId);
			}
			else
			{
				l.Beskrivning = form.FritextBeskrivning;
			}

			return l;
		}

		private static void CopyFromEntity(Materiel from, ClientMateriel to, bool minimal)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;
			to.Antal = from.Antal;
			to.ByggnadId = from.ByggnadId;

			to.Andrad = from.Andrad != null ? from.Andrad.ToString() : null;
			to.AndradAv = from.AndradAv;
			to.Skapad = from.Skapad != null ? from.Skapad.ToString() : null;
			to.SkapadAv = from.SkapadAv;
		}

		private static void CopyToEntity(ClientMateriel from, Materiel to)
		{
			to.Id = from.Id;
			to.ValId = from.ValId;
			to.Antal = from.Antal;
			to.ByggnadId = from.ByggnadId;

			if (!String.IsNullOrEmpty(from.Andrad))
				to.Andrad = DateTime.Parse(from.Andrad);
			else
				to.Andrad = null;

			to.AndradAv = from.AndradAv;

			if (from.Skapad != null)
				to.Skapad = DateTime.Parse(from.Skapad);

			to.SkapadAv = from.SkapadAv;
		}
	}
}
